package gui.client;

import java.awt.Color;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.text.MaskFormatter;

import control.LocalOpertaionController;
import control.LoginController;
import control.OrderController;
import system.FieldValidator;
import system.SystemMode;
import system.SystemTypes;
import system.VCP;
import vcpClasses.Client;
import vcpClasses.Order;
import vcpClasses.Rates;

import javax.swing.JComboBox;
import javax.swing.JTextField;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
 * this class use to create Occasional Customer Order 
 * @author G8
 *
 */
@SuppressWarnings("serial")
public class OccasionalCustomerOrderScreen extends JPanel implements ActionListener
{
	public JButton btnLogout;
	public JButton btnBack;
	public JButton btnSave;
	private JTextField IDNumber;
	private JTextField VehiclesNumber;
	private JFormattedTextField Email;
	private JLabel lblIDNumber;
	private JLabel lblVehiclesNumber;
	private JLabel lblEMail;
	private JLabel lblCheckOutTime;
	private OrderController orderControl;
	private JFormattedTextField textFieldCheckOut;
	private JButton btnEnter;
	private LocalOpertaionController localOpControl;
	/**
	 * Occasional Customer Order Constructor 
	 */
	public  OccasionalCustomerOrderScreen()
	{
		super();	
		initialize();
	}
	/**
	 * This method contains the view of the Panel
	 */
	private void initialize()
	{
		orderControl=new OrderController(null);
		localOpControl = new LocalOpertaionController(null);
		
		setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Occasional Order", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		setBackground(SystemColor.menu);
		setBounds(VCP.guiX,VCP.guiY,500,400);
		setLayout(null);
		VCP.frame.setBounds(this.getBounds());
		
		btnBack = new JButton("Back");
		btnBack.setIcon(new ImageIcon(AdvanceOrderScreen.class.getResource("/img/back.png")));
		btnBack.setSize(150, 30);
		btnBack.setBounds(281, 22, 102, 35);
		btnBack.addActionListener(this);
		add(btnBack);
		
		btnLogout = new JButton("Logout");
		btnLogout.setSize(150, 30);
		btnLogout.setBounds(393, 22, 78, 35);
		btnLogout.addActionListener(this);
		add(btnLogout);
		
		btnSave = new JButton("Create Order");
		btnSave.setBounds(169, 252, 131, 35);
		btnSave.addActionListener(this);
		add(btnSave);
		
		IDNumber = new JTextField();
		IDNumber.setBounds(273, 109, 86, 20);
		add(IDNumber);
		

		VehiclesNumber = new JTextField();
		VehiclesNumber.setBounds(273, 139, 86, 20);
		add(VehiclesNumber);
		
		Email = new JFormattedTextField();
		Email.setBounds(273, 198, 86, 20);
		add(Email);
		
		try {
			MaskFormatter formatTimeOut = new MaskFormatter("##:##");
			formatTimeOut.setValidCharacters("0123456789");
			textFieldCheckOut = new JFormattedTextField(formatTimeOut);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		textFieldCheckOut.setBounds(273, 171, 86, 20);
		add(textFieldCheckOut);
		textFieldCheckOut.setColumns(10);
		
		lblIDNumber = new JLabel("ID Number:");
		lblIDNumber.setBounds(140, 110, 160, 14);
		add(lblIDNumber);
		
		lblVehiclesNumber = new JLabel("Vehicle Number:");
		lblVehiclesNumber.setBounds(140, 140, 160, 14);
		add(lblVehiclesNumber);
		
		lblEMail = new JLabel("E-mail:");
		lblEMail.setBounds(140, 201, 160, 14);
		add(lblEMail);
		
		lblCheckOutTime = new JLabel("Check Out Time:");
		lblCheckOutTime.setBounds(140, 170, 160, 14);
		add(lblCheckOutTime);
		
		btnEnter = new JButton("Enter Vehicle");
		btnEnter.setEnabled(false);
		btnEnter.setBounds(169, 298, 131, 35);
		btnEnter.addActionListener(this);
		add(btnEnter);
		
	}
	
	
	
	/**
	 * This method listens to the buttons on the panel
	 * @param e is the buttons the user Click
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == btnSave)
		{
			IDNumber.setBackground(Color.WHITE);
			VehiclesNumber.setBackground(Color.WHITE);
			Email.setBackground(Color.WHITE);
			textFieldCheckOut.setBackground(Color.WHITE);
			
			if (FieldValidator.checkNumeric(IDNumber.getText()) && FieldValidator.checkNumeric(VehiclesNumber.getText())
					&& FieldValidator.checkEmail(Email.getText()) && FieldValidator.checkTime(textFieldCheckOut.getText())
					&& (Integer.parseInt(IDNumber.getText()) == ((Client)VCP.currentUser).getClientNumber()))
			{
				Date date = new Date();
				SimpleDateFormat thedate = new SimpleDateFormat("yyyy-MM-dd");
				String currDate = thedate.format(date);
				SimpleDateFormat thetime = new SimpleDateFormat("HH:mm");
				String currTime = thetime.format(date);
				
				
				System.out.println(VCP.currentLot.getParkingLotNumber());
				Order occasionalOrder = new Order(Integer.parseInt(IDNumber.getText()),Integer.parseInt(VehiclesNumber.getText()),
						textFieldCheckOut.getText(),Email.getText(),VCP.currentLot.getParkingLotNumber(),currDate,currTime,"OPEN","OCCASIONAL");
				occasionalOrder.setLeaveDate(CalculateDate(textFieldCheckOut.getText()));
				SystemTypes orderToCreate = new SystemTypes(occasionalOrder,null);
				SystemTypes setOrderResult = orderControl.createNewOrder(orderToCreate);
				if (setOrderResult.getSysMode().equals(SystemMode.OK)){
					JOptionPane.showMessageDialog(null, setOrderResult.getObj().toString(), "Success",JOptionPane.INFORMATION_MESSAGE);
					btnEnter.setEnabled(true);
					}
				else
					JOptionPane.showMessageDialog(null,setOrderResult.getObj().toString(), "Error",JOptionPane.ERROR_MESSAGE);
					
			}
			else
			{
				if (!FieldValidator.checkNumeric(IDNumber.getText())) IDNumber.setBackground(Color.RED);
				if (!FieldValidator.checkNumeric(VehiclesNumber.getText())) VehiclesNumber.setBackground(Color.RED);
				if (!FieldValidator.checkEmail(Email.getText())) Email.setBackground(Color.RED);
				if (!FieldValidator.checkTime(textFieldCheckOut.getText())) textFieldCheckOut.setBackground(Color.RED);
				JOptionPane.showMessageDialog(null,"Invalid field(s) detected !", "Error",JOptionPane.ERROR_MESSAGE);
			}
		}
		if (e.getSource() == btnEnter){
			Order order = new Order();
			order.setClientNumber(Integer.parseInt(IDNumber.getText()));
			order.setVehicleNumber(Integer.parseInt(VehiclesNumber.getText()));
			order.setSidParkingLocation(VCP.currentLot.getParkingLotNumber());
			order.setLeaveDate(CalculateDate(textFieldCheckOut.getText()));
			SystemTypes orderToEnter = new SystemTypes(order,null);
			SystemTypes enterResult = localOpControl.enterCar(orderToEnter);
			if (enterResult.getSysMode().equals(SystemMode.OK))
				JOptionPane.showMessageDialog(null, enterResult.getObj().toString(), "Success",JOptionPane.INFORMATION_MESSAGE);
			else
				JOptionPane.showMessageDialog(null,enterResult.getObj().toString(), "Error",JOptionPane.ERROR_MESSAGE);
		}
		
		if (e.getSource() == btnBack)
		{
			VCP.setScreen(this, VCP.prevScreen);
			VCP.prevScreen.setBounds(VCP.guiX,VCP.guiY,500,400);
			VCP.prevScreen.setLayout(null);
			VCP.frame.setBounds(VCP.prevScreen.getBounds());
		}
		
		if (e.getSource() == btnLogout)
		{
			SystemTypes userToLogout = new SystemTypes(VCP.currentUser,null);
			boolean logoutRes = LoginController.LogOut(userToLogout);
			if (logoutRes)
				VCP.setGUI(0, this);
			else
			{
				JOptionPane.showMessageDialog(null, "Failed to logout!", "Error",
	                    JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}
	
	public String CalculateDate(String orderTime){
		SimpleDateFormat thetime = new SimpleDateFormat("HHmm");
		String tr2 = thetime.format(new Date());
		orderTime = orderTime.replace(":", "");
		DateTimeFormatter fmt1 = DateTimeFormat.forPattern("yyyy-MM-dd");
		String date;
		int t1 = Integer.parseInt(orderTime);
		int t2 = Integer.parseInt(tr2);
		if (t2<t1)
		{
			date = fmt1.print((new DateTime()));
		}
		else 
		{
			date = fmt1.print((new DateTime()).plusDays(1));
			}
		return date;
	}
}
